<template>
    <el-row class="lives-news">
        <el-col class="title">
            <h3>{{isAdd ? '新增' : '修改'}}文章</h3>
        </el-col>
        <el-col>
            <el-form :model="formInline" label-width="120px">
                <el-form-item label="文章标题">
                    <el-input type="text" v-model="formInline.articleTitle" auto-complete="off" placeholder="请输入文章标题"></el-input>
                </el-form-item>
                <el-form-item label="文章分类">
                    <el-select v-model="formInline.articleCategoryId" filterable placeholder="请选择文章分类">
                        <el-option label="请选择" :value="null"></el-option>
                        <el-option v-for="item in articleCategoryList" :key="item.articleCategoryId" :label="item.articleCategoryName" :value="item.articleCategoryId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布时间">
                    <el-date-picker
                          v-model="formInline.time"
                          type="datetime"
                          placeholder="发布时间,不填默认今天"
                          @change="showTime">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="缩略图">
                    <el-upload class="avatar-uploader" :headers="uploadHeader" :action="BASEURL+'/upload/headerImgUrl'" :show-file-list="false" :on-success="handleThumbSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    <el-button v-if="headerImgUrl" size="small" type="danger" @click="empty">删 除</el-button>
                    <div>
                        <img v-if="headerImgUrl" :src="UPLOADURL+headerImgUrl" alt="" class="banner-thumb">
                    </div>
                </el-form-item>
                <el-form-item v-if="formInline.articleCategoryId==17025239904944128" label="活动图片">
                    <el-upload class="avatar-uploader" :headers="uploadHeader" :action="BASEURL+'/upload/activity'" :show-file-list="false" :on-success="handleAvatarSuccess">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    <div>
                        <img v-if="imageUrl" :src="UPLOADURL+imageUrl" alt="" class="banner-thumb">
                    </div>
                </el-form-item>
                <div v-else>
                    <el-form-item label="是否原创">
                        <el-switch
                          v-model="origin"
                          on-text="是"
                          off-text="否"
                          off-color="#ff4949">
                        </el-switch>
                    </el-form-item>
                    <el-form-item v-if="!origin" label="链接地址">
                        <el-input type="text" v-model="formInline.jumpUrl" auto-complete="off" placeholder="请输入文章跳转的地址"></el-input>
                    </el-form-item>
                    <el-form-item v-else class="quill-box" label="文章内容">
                        <quill-editor class="quill" v-model="formInline.articleContent" ref="myQuillEditor" :options="editorOption">
                        </quill-editor>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="update">保 存</el-button>
                    <el-button type="danger" @click="gotoList">取 消</el-button>
                </el-form-item>
            </el-form>
            <form action="" method="post" enctype="multipart/form-data" id="uploadFormMulti">
       			<input style="display: none" :id="uniqueId" type="file" name="file" multiple accept="image/jpg,image/jpeg,image/png,image/gif" @change="uploadImg('uploadFormMulti')"><!--style="display: none"-->
     		</form>
        </el-col>
    </el-row>
</template>
<script>
import {
    getArticleCategoryList,
    getArticleById,
    addArticle,
    updateArticleById,
    uploadFiles
} from '@/api/api'
import {quillEditor, Quill} from 'vue-quill-editor'
import ImageResize from 'quill-image-resize-module'

Quill.register('modules/ImageResize', ImageResize)

export default {
    components: {
        quillEditor
    },
    data() {
        return {
        	uniqueId: 'uploadImageFile',
        	addImgRange: null,
        	imageLoading: false,
            formInline: {
                articleId: 0,
                articleCategoryId: null,
                articleTitle: '',
                articleContent: '',
                headerImgUrl: '',
                jumpUrl: null,
                time: null
            },
            editorOption :{
            	modules: {
                    ImageResize: {}
            	}
            },
            articleCategoryList : [],
            isAdd : false,
            origin: true,
            uploadHeader: {
                TOKEN: sessionStorage.getItem('jwt'),
                APPID: 1
            },
            imageUrl: '',
            headerImgUrl: ''
        }
    },
    created() {
        this.isAdd = this.$route.path.indexOf("Update") == -1;
        
        if (!this.isAdd){
            getArticleById(this.$route.query.articleId).then(data => {

                this.formInline = data;
                this.headerImgUrl = data.headerImgUrl
                if(data.articleCategoryType == 'activity'){
                    this.imageUrl = data.articleContent;
                }
                getArticleCategoryList(data).then(res => {
                    this.articleCategoryList = res;
                })
            })
        } else {
            getArticleCategoryList().then(res => {
                this.articleCategoryList = res;
            })
        }
    },
    mounted() {
    	var me = this;
    	var quill = me.$refs.myQuillEditor.quill;
    	var imgHandler = async function(image) {
    		me.addImgRange = quill.getSelection()
    		if (image) {
    			var fileInput = document.getElementById(me.uniqueId) //隐藏的file文本ID
    			fileInput.click() //加一个触发事件
    		}
    	}
    	quill.getModule("toolbar").addHandler("image", imgHandler)
    },
    methods: {
    	uploadImg: async function(id) {
            var me = this
        	var quill = me.$refs.myQuillEditor.quill;
			var fileDom = document.getElementById(me.uniqueId)
			
			var file = fileDom.files[0];

            var formData = new FormData()
            formData.append('file', file);
            formData.path = '/article'
            
            uploadFiles(formData).then(res => {
            	var webUrl = this.UPLOADURL + res.webPath;
            	
            	quill.insertEmbed(me.addImgRange != null ? me.addImgRange.index : 0, 'image', webUrl, Quill.sources.USER)
            })
        },
        update(){
            if(this.formInline.articleTitle == ''){
                this.$message({
                    message: '请输入文章标题',
                    type: 'error'
                })
                return;
            }
            if(this.formInline.articleCategoryId === null){
                this.$message({
                    message: '请选择文章分类',
                    type: 'error'
                })
                return;
            }
            if(this.formInline.articleCategoryId == '17025239904944128' && this.formInline.articleContent == ''){
                this.$message({
                    message: '请输入文章内容',
                    type: 'error'
                })
                return;
            }
            if(this.origin && this.formInline.articleContent == ''){
                this.$message({
                    message: '请输入文章内容',
                    type: 'error'
                })
                return;
            }
            if(!this.origin && this.formInline.jumpUrl == null){
                this.$message({
                    message: '请输入文章跳转的地址',
                    type: 'error'
                })
                return;
            }
            if (this.isAdd) {
                addArticle(this.formInline).then(data => {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    })
                    this.gotoList();
                })
            } else {
                updateArticleById(this.formInline).then(data => {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    })
                    this.gotoList();
                })
            }
        },
        gotoList(){
            this.$router.back()
        },
        handleAvatarSuccess(res){
            if(res.status){
                this.$message({
                    message: '上传成功',
                    type: 'success'
                })
                this.imageUrl = res.data.webPath;
                this.formInline.articleContent = res.data.webPath;
            }else{
                this.$message({
                    message: '上传失败',
                    type: 'error'
                })
            }
        },
        showTime: function(val){
            this.formInline.time = new Date(val).getTime()
        },
        handleThumbSuccess: function(res){
            if(res.status){
                this.$message({
                    message: '上传成功',
                    type: 'success'
                })
                this.headerImgUrl = res.data.webPath;
                this.formInline.headerImgUrl = res.data.webPath;
            }else{
                this.$message({
                    message: '上传失败',
                    type: 'error'
                })
            }
        },
        empty: function(){
            this.$confirm('是否删除缩略图?', '删除缩略图', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.headerImgUrl = '';
                this.formInline.headerImgUrl = '';
                this.$message({
                    type: 'info',
                    message: '操作成功'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            
        }
    }
}
</script>
<style scoped lang="scss">
.quill-box {
    min-height: 650px;
    .quill { 
        min-height: 550px;
    }
}
.lives-news {
    .title {
        font-size: 12px;
        border-bottom: 1px solid #eaeaea;
        margin-bottom: 5px;
        h3 {
            display: inline-block;
            padding: 5px 0;
            margin: 0;
            font-weight: normal;
            color: #23b7e5;
            border-bottom: 1px solid #23b7e5;
        }
    }
}
.avatar-uploader{
    display: inline-block;
}
.banner-thumb{
    width: 100px;
}
</style>